package com.dzx.permissionmanagersystem.service;

import com.dzx.permissionmanagersystem.dao.SysDeptMapper;
import com.dzx.permissionmanagersystem.dto.DeptLevelDto;
import com.dzx.permissionmanagersystem.entity.SysDept;
import com.dzx.permissionmanagersystem.util.LevelUtil;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author DuanZhaoXu
 * @ClassName:
 * @Description:
 * @date 2018年11月29日 14:42:56
 */
@Service
public class SysTreeService {


    @Resource
    private SysDeptMapper deptMapper;



    public List<DeptLevelDto> deptTree(){
      List<SysDept> deptList =deptMapper.getAllDept();
      List<DeptLevelDto> dtoList = deptList.parallelStream().map(DeptLevelDto::adapt).collect(Collectors.toList());
      return deptListToTree(dtoList);
    }


    public   List<DeptLevelDto>  deptListToTree( List<DeptLevelDto> deptLevelList){
          if(CollectionUtils.isEmpty(deptLevelList)){
              return Lists.newArrayList();
          }
        Multimap<String,DeptLevelDto> levelDeptMap = ArrayListMultimap.create();
        List<DeptLevelDto> rootList = Lists.newArrayList();
       for(DeptLevelDto dto : deptLevelList){
            levelDeptMap.put(dto.getLevel(),dto);
            if(LevelUtil.ROOT.equals(dto.getLevel())){
                 rootList.add(dto);
            }
       }
       //按照 seq 从小到大排序
        Collections.sort(rootList,deptLevelDtoComparator);

        transformDeptTree(rootList,LevelUtil.ROOT,levelDeptMap);
        return rootList;

    }


    public   Comparator<DeptLevelDto> deptLevelDtoComparator = new Comparator<DeptLevelDto>() {
        @Override
        public int compare(DeptLevelDto o1, DeptLevelDto o2) {
            return o1.getSeq() - o2.getSeq();
        }
    };


    public  void transformDeptTree(List<DeptLevelDto> deptLevelDtoList,String level, Multimap<String,DeptLevelDto> levelDeptMap){
         for(int i =0;i<deptLevelDtoList.size();i++){
            DeptLevelDto deptLevelDto = deptLevelDtoList.get(i);
            //处理当前层级数据
            String  nextLevel = LevelUtil.calculateLevel(level,deptLevelDto.getId());
            //处理下一层
             List<DeptLevelDto> tempDeptList= (List<DeptLevelDto>) levelDeptMap.get(nextLevel);
              if(CollectionUtils.isNotEmpty(tempDeptList)){
                  Collections.sort(tempDeptList,deptLevelDtoComparator);
                  deptLevelDto.setDeptList(tempDeptList);
                  //进入到下一层处理
                  transformDeptTree(tempDeptList,nextLevel,levelDeptMap);
              }
         }
    }


}
